"""提供层弹出相关功能的服务类."""
from datetime import datetime
from typing import List
from cachetools import LFUCache, cached
from cachetools.keys import hashkey
from fastapi import Request
from sqlalchemy import between, select
from sqlalchemy.orm import Session

from core.database import db_session
from core.exception import AlertException
from core.models import NewWin
from service import BaseService


class NewWinService(BaseService):
    """提供层弹出相关功能的类."""
    current_division = "comm"  # comm, both, shop (仅使用当前社区)

    def __init__(self, request: Request, db: Session):
        self.request = request
        self.db = db

    @classmethod
    async def async_init(cls, request: Request, db: db_session):
        """用Adong初始化类的函数"""
        instance = cls(request, db)
        return instance

    def raise_exception(self, status_code: int, detail: str = None, url: str = None):
        return AlertException(detail=detail, status_code=status_code, url=url)

    @cached(LFUCache(maxsize=256), key=lambda self, device="pc": hashkey("newwins", device))
    def fetch_newwins(self, device: str = "pc") -> List[NewWin]:
        """
        在数据库中查看层弹出列表。
        """
        now = datetime.now().strftime("%Y-%m-%d %H:%M:%S")

        newwins = self.db.scalars(
            select(NewWin).where(
                between(now, NewWin.nw_begin_time, NewWin.nw_end_time),
                NewWin.nw_device.in_(["both", device]),
                NewWin.nw_division.in_(["both", self.current_division]),
            ).order_by(NewWin.nw_id)
        ).all()

        return newwins

    def get_newwins_except_cookie(self):
        """
       如果您正在检查是否存在以“hd_pops_”+nw_id名称声明的Cookie，请删除弹出窗口
        """
        device = getattr(self.request.state, "device", "pc")
        newwins = self.fetch_newwins(device)

        # 
        return [newwin for newwin in newwins
                if not self.request.cookies.get("hd_pops_" + str(newwin.nw_id))]
